package top.xiaozhaobk.xiaofenshu.oss.biz.strategy.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import top.xiaozhaobk.xiaofenshu.oss.biz.config.AliyunOSSProperties;
import top.xiaozhaobk.xiaofenshu.oss.biz.enums.ResponseCodeEnum;
import top.xiaozhaobk.xiaofenshu.oss.biz.strategy.FileStrategy;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/*
AccessKey ID  LTAI5t6UZ75V5oYXa6sdxGu2
AccessKey Secret  xt8LDbkWNxkL6QfJoTw1CUPYN2cAvU
 */
@Slf4j
public class AliyunOSSFileStrategy implements FileStrategy {
    @Resource
    private OSS ossClient;
    @Resource
    private AliyunOSSProperties aliyunOSSProperties;

    @Override
    public String uploadFile(MultipartFile file, String bucketName) {
        log.info("使用阿里云OSS上传文件");

        if (file == null || file.getSize() == 0) {
            log.error("==>上传文件异常：文件大小为空");
            throw new RuntimeException("文件大小不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();

        //创建新的文件名
        String newName = UUID.randomUUID().toString().replace("-", "");
        //获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接文件名
        String objectName = String.format("%s%s", newName, suffix);

        log.info("==> 开始上传文件至阿里云OSS, ObjectName: {}", objectName);
        try {
            ossClient.putObject(bucketName,objectName,new ByteArrayInputStream(file.getInputStream().readAllBytes()));
        } catch (IOException e) {
            log.error("==> 上传文件至阿里云OSS失败, ObjectName: {}", objectName);
            throw new RuntimeException(ResponseCodeEnum.PARAM_NOT_VALID.getErrorMessage());
        }

        String url = String.format("https://%s.%s/%s", bucketName, aliyunOSSProperties.getEndpoint(), objectName);
        log.info("==> 上传文件至阿里云OSS成功, ObjectName: {}, url: {}", objectName, url);
        return url;
    }
}
